﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace MyLibrary.Collections.Generic
{
    /// <summary>
    /// 可以设定排序规则的SortedList
    /// </summary>
    /// <typeparam name="TKey">键</typeparam>
    /// <typeparam name="TValue">值</typeparam>
    [Serializable,ComVisible(false),DebuggerDisplay("Count = {Count}")]
    public class ReversibleSortedList<TKey,TValue> : IDictionary<TKey,TValue>,ICollection<KeyValuePair<TKey,TValue>>,
        IEnumerable<KeyValuePair<TKey,TValue>>,IDictionary,ICollection,IEnumerable
    {
        #region 实现排序方式的内部类
        /// <summary>
        /// 实现排序方式的内部类
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        public class SortDirectionComparer<T> : IComparer<T>
        {
            //排序的方式
            private ListSortDirection _sortDir;
            /// <summary>
            /// 构造函数,默认升序
            /// </summary>
            public SortDirectionComparer()
            {
                _sortDir = ListSortDirection.Ascending;
            }

            /// <summary>
            /// 构造函数,指定排序方式
            /// </summary>
            /// <param name="sortDir">排序方式</param>
            public SortDirectionComparer(ListSortDirection sortDir)
            {
                _sortDir = sortDir;
            }

            /// <summary>
            /// 设置排序的方法
            /// </summary>
            public ListSortDirection SortDirection
            {
                get { return _sortDir; }
                set { _sortDir = value; }
            }

            #region IComparer<T> Members

            /// <summary>
            /// 实现的排序方法
            /// </summary>
            /// <param name="x">排序值1</param>
            /// <param name="y">排序值2</param>
            /// <returns>比较的结果</returns>
            public int Compare(T x, T y)
            {
                int result = x.ToString().CompareTo(y.ToString());

                if (_sortDir == ListSortDirection.Descending)
                    result *= -1;
                return result;
            }

            #endregion
        }
        #endregion

        #region Fields
        private int _size;
        private const int _defaultCapacity = 4;
        private int version;
        private ListSortDirection _currentSortDirection;
        private SortDirectionComparer<TKey> _sortDirectionComparer = null;
        private TKey[] keys;
        private TValue[] values;
        private static TKey[] emptyKeys;    //内部静态键集合(默认)
        private static TValue[] emptyValues;//内部静态值集合(默认)
        private KeyList<TKey, TValue> keyList;
        private ValueList<TKey, TValue> valueList;
        #endregion

        #region 公有类属性
        /// <summary>
        /// 集合的容量(只读)
        /// </summary>
        public int Capacity
        {
            get { return this.keys.Length; }
            set { InternalSetCapactity(value, true); }
        }

        /// <summary>
        /// 排序的方法(只读)
        /// </summary>
        public SortDirectionComparer<TKey> Comparer
        {
            get { return this._sortDirectionComparer; }
        }
        /// <summary>
        /// 集合的当前元素数量(只读)
        /// </summary>
        public int Count
        {
            get { return this._size; }
        }
        /// <summary>
        /// 获取指定键的集合值
        /// </summary>
        /// <param name="key">指定的键</param>
        /// <returns>对应的值</returns>
        public TValue this[TKey key]
        {
            get 
            {
                int num1 = this.IndexOfKey(key);
                if (num1 >= 0)
                    return values[num1];
                else
                    return default(TValue);
            }
            set
            {
                if (key == null)
                    throw new ArgumentNullException("key");
                int num1 = Array.BinarySearch<TKey>(keys, 0, _size, key, _sortDirectionComparer);
                if (num1 >= 0)
                {
                    this.values[num1] = value;
                    this.version++;
                }
                else
                    this.Insert(~num1, key, value);
            }
        }

        /// <summary>
        /// 键的集合(只读)
        /// </summary>
        public IList<TKey> Keys
        {
            get { return this.GetKeyListHelper(); }
        }

        /// <summary>
        /// 值的集合(只读)
        /// </summary>
        public IList<TValue> Values
        {
            get { return this.GetValueListHelper(); }
        }
        #endregion

        #region 私有类属性
        bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
        {
            get{return false;}
        }

        ICollection<TKey> IDictionary<TKey, TValue>.Keys
        {
            get{return this.GetKeyListHelper();}
        }

        ICollection<TValue> IDictionary<TKey, TValue>.Values
        {
            get{return this.GetValueListHelper();}
        }

        bool ICollection.IsSynchronized
        {
            get{return false;}
        }

        object ICollection.SyncRoot
        {
            get{return this;}
        }

        bool IDictionary.IsFixedSize
        {
            get{return false;}
        }

        bool IDictionary.IsReadOnly
        {
            get{return false;}
        }

        object IDictionary.this[object key]
        {
            get
            {
                if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey(key))
                {
                    int num1 = this.IndexOfKey((TKey)key);
                    if (num1 >= 0)
                    {
                        return this.values[num1];
                    }
                }
                return null;
            }
            set
            {
                ReversibleSortedList<TKey, TValue>.VerifyKey(key);
                ReversibleSortedList<TKey, TValue>.VerifyValue(value);
                this[(TKey)key] = (TValue)value;
            }
        }

        ICollection IDictionary.Keys
        {
            get{return this.GetKeyListHelper();}
        }

        ICollection IDictionary.Values
        {
            get{return this.GetValueListHelper();}
        }
        #endregion

        #region 构造函数
        //类型构造
        static ReversibleSortedList()
        {
            ReversibleSortedList<TKey, TValue>.emptyKeys = new TKey[0];
            ReversibleSortedList<TKey, TValue>.emptyValues = new TValue[0];
        }

        /// <summary>
        /// 无参数构造函数
        /// </summary>
        public ReversibleSortedList()
        {
            this.keys = ReversibleSortedList<TKey, TValue>.emptyKeys;
            this.values = ReversibleSortedList<TKey, TValue>.emptyValues;
            this._size = 0;
            this._sortDirectionComparer = new ReversibleSortedList<TKey, TValue>.SortDirectionComparer<TKey>();
            this._currentSortDirection = this._sortDirectionComparer.SortDirection;
        }

        /// <summary>
        /// 使用指定排序方法的构造函数
        /// </summary>
        /// <param name="comparer">构造方法</param>
        public ReversibleSortedList(SortDirectionComparer<TKey> comparer)
            : this()
        {
            if (comparer != null)
            {
                this._sortDirectionComparer = comparer;
                this._currentSortDirection = comparer.SortDirection;
            }
        }

        /// <summary>
        /// 用于指定的字典的构造函数
        /// </summary>
        /// <param name="dictionary"></param>
        public ReversibleSortedList(IDictionary<TKey, TValue> dictionary)
            : this(dictionary, (SortDirectionComparer<TKey>)null)
        {

        }

        /// <summary>
        /// 用于指定集合元素大小的构造方法
        /// </summary>
        /// <param name="capactity"></param>
        public ReversibleSortedList(int capactity)
        {
            if (capactity < 0)
                throw new ArgumentOutOfRangeException("capactity", "集合初始化容量不能为空");

            this.keys = new TKey[capactity];
            this.values = new TValue[capactity];
            this._sortDirectionComparer = new ReversibleSortedList<TKey, TValue>.SortDirectionComparer<TKey>();
            this._currentSortDirection = this._sortDirectionComparer.SortDirection;
        }

        /// <summary>
        /// 对指定的字典表使用指定的排序方式的构造方法
        /// </summary>
        /// <param name="dictionary">指定的字典表</param>
        /// <param name="comparer">排序方法</param>
        public ReversibleSortedList(IDictionary<TKey, TValue> dictionary, SortDirectionComparer<TKey> comparer)
            : this((dictionary != null) ? dictionary.Count : 0, comparer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            dictionary.Keys.CopyTo(this.keys, 0);
            dictionary.Values.CopyTo(this.values, 0);
            Array.Sort<TKey, TValue>(this.keys, this.values, this._sortDirectionComparer);
            this._size = dictionary.Count;
        }

        /// <summary>
        /// 使用指定的容量和排序方法的构造函数
        /// </summary>
        /// <param name="capactity">指定容量</param>
        /// <param name="comparer">排序方法</param>
        public ReversibleSortedList(int capactity, SortDirectionComparer<TKey> comparer)
            : this(comparer)
        {
            this.Capacity = capactity;
        }

        #endregion

        #region 类公有方法
        /// <summary>
        /// 向集合添加元素
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <exception cref="ArgumentException"></exception>
        public void Add(TKey key, TValue value)
        {
            if (key.Equals(null))
                throw new ArgumentNullException("key");
            int num1 = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this._sortDirectionComparer);

            if (num1 >= 0)
                throw new ArgumentException("不能插入重复值");

            Insert(~num1, key, value);
        }

        /// <summary>
        /// 清空集合的元素
        /// </summary>
        public void Clear()
        {
            this.version++;
            Array.Clear(keys, 0, this._size);
            Array.Clear(values, 0, this._size);
            this._size = 0;
        }

        /// <summary>
        /// 集合中是否包含指定的键
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>是否包含</returns>
        public bool ContainsKey(TKey key)
        {
            return (IndexOfKey(key) >= 0);
        }

        /// <summary>
        /// 集合中是否包含指定的值
        /// </summary>
        /// <param name="key">值</param>
        /// <returns>是否包含</returns>
        public bool ContainsValue(TValue value)
        {
            return (IndexOfValue(value) >= 0);
        }

        /// <summary>
        /// 得到集合的简单枚举
        /// </summary>
        /// <returns>集合的简单枚举</returns>
        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(this);
        }
        /// <summary>
        /// 查找指定的键的索引
        /// </summary>
        /// <param name="key">键值</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>指定的键在集合中的索引,不存在返回-1</returns>
        public int IndexOfKey(TKey key)
        {
            if (key.Equals(null))
                throw new ArgumentNullException("key");
            int num1 = Array.BinarySearch(keys, 0, _size, key);
            if (num1 < 0)
                return -1;
            return num1;
        }

        /// <summary>
        /// 查找指定的值的索引
        /// </summary>
        /// <param name="value">指定的值</param>
        /// <returns>值所在的位置</returns>
        public int IndexOfValue(TValue value)
        {
            return Array.IndexOf<TValue>(values, value, 0, _size);
        }
        
        /// <summary>
        /// 移除指定的Key
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns>是否存在指定的Key</returns>
        public bool Remove(TKey key)
        {
            int num1 = IndexOfKey(key);
            if (num1 >= 0)
                this.RemoveAt(num1);
            return (num1 >= 0);
        }

        /// <summary>
        /// 移除指定索引位置的值
        /// </summary>
        /// <param name="index">索引位</param>
        public void RemoveAt(int index)
        {
            if (index < 0 || index >= this._size)
                throw new ArgumentOutOfRangeException("index", "索引超过集合元素数量");
            this._size--;
            if (index < this._size)
            {
                Array.Copy(this.keys, index + 1, this.keys, index, this._size - index);
                Array.Copy(this.values, index + 1, this.values, index, this._size - index);
            }
            this.keys[this._size] = default(TKey);
            this.values[this._size] = default(TValue);
            this.version++;
        }

        /// <summary>
        /// 对集合中的元素进行排序
        /// </summary>
        public void Sort()
        {
            //检查是否与当期的排序规则相同
            if (this._currentSortDirection != this._sortDirectionComparer.SortDirection)
            {
                //如果不相同则进行反转
                Array.Reverse(this.keys, 0, this._size);
                Array.Reverse(this.values, 0, this._size);
                //设置当期的排序
                this._currentSortDirection = this._sortDirectionComparer.SortDirection;
            }
        }
        
        /// <summary>
        /// 剪除多余的空间
        /// </summary>
        /// <remarks>当期集合的数量小于指定容量的90%时函数有效</remarks>
        public void TrimExcess()
        {
            int num1 = (int)(this.keys.Length * 0.9);
            if (this._size < num1)
                this.Capacity = this._size;
        }

        /// <summary>
        /// 尝试获取指定键的值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>是否获取成功</returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            int num1 = this.IndexOfKey(key);
            if (num1 >= 0)
            {
                value = this.values[num1];
                return true;
            }
            value = default(TValue);
            return false;
        }
        #endregion

        #region 类私有方法
        /// <summary>
        /// 设置集合的容量
        /// </summary>
        /// <param name="value">容量值</param>
        /// <param name="updateVersion">是否更新版本</param>
        private void InternalSetCapactity(int value, bool updateVersion)
        {
            if (value != this.keys.Length)
            {
                if (value < this._size)
                    throw new ArgumentOutOfRangeException("value", "设置的容量太小");
                if (value > 0)
                {
                    TKey[] localArray1 = new TKey[value];
                    TValue[] localArray2 = new TValue[value];
                    if (this._size > 0)
                    {
                        Array.Copy(this.keys, 0, localArray1, 0, this._size);
                        Array.Copy(this.values, 0, localArray2, 0, this._size);
                    }
                    this.keys = localArray1;
                    this.values = localArray2;
                }
                else
                {
                    this.keys = ReversibleSortedList<TKey, TValue>.emptyKeys;
                    this.values = ReversibleSortedList<TKey, TValue>.emptyValues;
                }

                if (updateVersion)
                    this.version++;
            }
        }
        /// <summary>
        /// 确认容量是否达到指定的值
        /// </summary>
        /// <param name="min">指定的值</param>
        private void EnsureCapacity(int min)
        {
            int num1 = (this.keys.Length == 0) ? 4 : (this.keys.Length * 2);
            if (num1 < min)
                num1 = min;
            this.InternalSetCapactity(num1, false);
        }
        /// <summary>
        /// 得到指定位置索引位置的数据
        /// </summary>
        /// <param name="index">索引位</param>
        /// <returns>返回值</returns>
        private TValue GetIndexKey(int index)
        {
            if (index < 0 || index >= this._size)
                throw new ArgumentException("index");

            return this.values[index];
        }
        /// <summary>
        /// 得到指定位置的键值
        /// </summary>
        /// <param name="index">索引位</param>
        /// <returns>返回值</returns>
        private TKey GetIndexValue(int index)
        {
            if (index < 0 || index >= this._size)
                throw new ArgumentException("index");

            return this.keys[index];
        }
        private KeyList<TKey, TValue> GetKeyList()
        {
            if (this.keyList == null)
                this.keyList = new KeyList<TKey, TValue>(this);
            return this.keyList;
        }
        /// <summary>
        /// 在指定的位置插入值
        /// </summary>
        /// <param name="index">指定的位置</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        private void Insert(int index, TKey key, TValue value)
        {
            if (this._size == this.keys.Length)
                EnsureCapacity(this._size + 1);

            if (index < this._size)
            {
                //将内部数组从Index位向后衍生一位
                Array.Copy(this.keys, index, this.keys, index + 1, this._size - index);
                Array.Copy(this.values, index, this.values, index + 1, this._size - index);
            }
            this.keys[index] = key;
            this.values[index] = value;
            this._size++;
            this.version++;
        }

        /// <summary>
        /// 校验Key的类型是否正确
        /// </summary>
        /// <param name="key">要校验的Key</param>
        private static void VerifyKey(object key)
        {
            if (key.Equals(null))
                throw new ArgumentNullException("key");
            if (!(key is TKey))
                throw new ArgumentException("指定的参数类型错误", "key");
        }

        /// <summary>
        /// 校验Key的类型是否正确
        /// </summary>
        /// <param name="key">要校验的Key</param>
        private static void VerifyValue(object value)
        {
            if (value.Equals(null))
                throw new ArgumentNullException("value");
            if (!(value is TValue) || typeof(TValue).IsValueType)
                throw new ArgumentException("指定的参数类型错误", "value");
        }

        /// <summary>
        /// 判断指定的Object类型的值是否为集合类型
        /// </summary>
        /// <param name="key">要判断的Object值</param>
        /// <returns>判断结果</returns>
        private static bool IsCompatibleKey(object key)
        {
            if (key.Equals(null))
                throw new ArgumentNullException("key");
            return key is TKey;
        }

        /// <summary>
        /// 得到集合中键的集合
        /// </summary>
        /// <returns>键集合</returns>
        private ValueList<TKey, TValue> GetValueListHelper()
        {
            if (this.valueList == null)
                this.valueList = new ReversibleSortedList<TKey, TValue>.ValueList<TKey, TValue>(this);
            return this.valueList;
        }

        /// <summary>
        /// 得到集合中值的集合
        /// </summary>
        /// <returns>值集合</returns>
        private KeyList<TKey, TValue> GetKeyListHelper()
        {
            if (this.keyList == null)
                this.keyList = new ReversibleSortedList<TKey, TValue>.KeyList<TKey, TValue>(this);
            return this.keyList;
        }

        /// <summary>
        /// 显示的实现接口成员
        /// </summary>
        void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
        {
            this.Add(keyValuePair.Key, keyValuePair.Value);
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
        {
            int num1 = this.IndexOfKey(keyValuePair.Key);
            if (num1 >= 0 && EqualityComparer<TValue>.Default.Equals(this.values[num1], keyValuePair.Value))
                return true;
            return false;
        }

        void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array");
            if (arrayIndex < 0 || arrayIndex > array.Length)
                throw new ArgumentOutOfRangeException("arrayIndex", "数组超界");
            if (array.Length - arrayIndex < this.Count)
                throw new ArgumentException("Array Plus Off Too Small");

            for (int num1 = 0; num1 < this.Count; num1++)
            {
                KeyValuePair<TKey, TValue> pari1;
                pari1 = new KeyValuePair<TKey,TValue>(this.keys[num1],this.values[num1]);
                array[arrayIndex + num1] = pari1;
            }
        }

        void ICollection.CopyTo(Array array, int index)
        {
            if (array == null)
                throw new ArgumentNullException("array");
            if (array.Rank != 1)
                throw new ArgumentException("MultiDimensional array copies are not supported");
            if (array.GetLowerBound(0) != 0)
                throw new ArgumentException("A not-zero lower bound was provided");
            if (index < 0 || index > array.Length)
                throw new ArgumentOutOfRangeException("index", "Need no negative number");
            if (array.Length - index < this._size)
                throw new ArgumentException("Array plus the offest is too small");

            KeyValuePair<TKey, TValue>[] pairArray1 = array as KeyValuePair<TKey, TValue>[];
            if (pairArray1 != null)
            {
                for (int num1 = 0; num1 < this.Count; num1++)
                    pairArray1[num1 + index] = new KeyValuePair<TKey, TValue>(this.keys[num1], this.values[num1]);
            }
            else
            {
                object[] objArray1 = array as object[];
                if(objArray1 == null)
                    throw new ArgumentException("数组类型不正确");

                try
                {
                    for (int num2 = 0; num2 < this.Count; num2++)
                        objArray1[num2 + index] = new KeyValuePair<TKey, TValue>(this.keys[num2], this.values[num2]);
                }
                catch (ArrayTypeMismatchException)
                {
                    throw new ArgumentException("数组类型不正确");
                }
            }
        }

        void IDictionary.Add(object key, object value)
        {
            ReversibleSortedList<TKey, TValue>.VerifyKey(key);
            ReversibleSortedList<TKey, TValue>.VerifyValue(value);
            this.Add((TKey)key, (TValue)value);
        }

        bool IDictionary.Contains(object key)
        {
            if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey(key))
                return this.ContainsKey((TKey)key);
            return false;
        }

        void IDictionary.Remove(object key)
        {
            if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey((TKey)key))
                Remove((TKey)key);
        }

        IDictionaryEnumerator IDictionary.GetEnumerator()
        {
            return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(this);
        }

        IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
        {
            return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(this);
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
        {
            int num1 = this.IndexOfKey(item.Key);
            if ((num1 >= 0) && EqualityComparer<TValue>.Default.Equals(this.values[num1], item.Value))
            {
                this.RemoveAt(num1);
                return true;
            }
            return false;
        }

        #endregion

        #region 私有结构体
        [Serializable, StructLayout(LayoutKind.Sequential)]
        private struct Enumerator<K, V> : IEnumerator<KeyValuePair<K, V>>, IDisposable, IDictionaryEnumerator, IEnumerator
        {
            private ReversibleSortedList<K, V> _ReversibleSortedList;
            private K key;
            private V value;
            private int index;
            private int version;

            internal Enumerator(ReversibleSortedList<K, V> ReversibleSortedList)
            {
                this._ReversibleSortedList = ReversibleSortedList;
                this.index = 0;
                this.version = this._ReversibleSortedList.version;
                this.key = default(K);
                this.value = default(V);
            }

            public void Dispose()
            {
                this.index = 0;
                this.key = default(K);
                this.value = default(V);
            }

            object IDictionaryEnumerator.Key
            {
                get
                {
                    if (this.index == 0 || this.index == this._ReversibleSortedList.Count + 1)
                        throw new InvalidOperationException("不能对集合的键进行枚举操作");
                    return this.key;
                }
            }

            public bool MoveNext()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("在枚举过程中集合元素发生变化");
                if (this.index < this._ReversibleSortedList.Count)
                {
                    this.key = this._ReversibleSortedList.keys[this.index];
                    this.value = this._ReversibleSortedList.values[this.index];
                    this.index++;
                    return true;
                }
                this.index = this._ReversibleSortedList.Count + 1;
                this.key = default(K);
                this.value = default(V);
                return false;
            }

            DictionaryEntry IDictionaryEnumerator.Entry
            {
                get
                {
                    if (this.index == 0 || this.index == this._ReversibleSortedList.Count + 1)
                        throw new InvalidOperationException("不能对集合的键进行枚举操作");
                    return new DictionaryEntry(this.key, this.value);
                }
            }

            public KeyValuePair<K, V> Current
            {
                get { return new KeyValuePair<K, V>(this.key, this.value); }
            }

            object IEnumerator.Current
            {
                get
                {
                    if (this.index == 0 || this.index == (this._ReversibleSortedList.Count + 1))
                        throw new InvalidOperationException("Enumeration operation cannot occur");
                    return new DictionaryEntry(this.key, this.value);
                }
            }

            object IDictionaryEnumerator.Value
            {
                get
                {
                    if (this.index == 0 || this.index == (this._ReversibleSortedList.Count + 1))
                        throw new InvalidOperationException("Enumeration operation cannot occur");
                    return this.value;
                }
            }

            void IEnumerator.Reset()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("Enumeration version check failed");
                this.index = 0;
                this.key = default(K);
                this.value = default(V);
            }
        }
        #endregion

        #region 内部类
        /// <summary>
        /// 实现字典集合内部的键的操作
        /// </summary>
        [Serializable]
        private sealed class KeyList<K, V> : IList<K>, ICollection<K>, IEnumerable<K>, ICollection, IEnumerable
        {
            //变量
            private ReversibleSortedList<K, V> _dict;
            //属性
            /// <summary>
            /// 获取一个值,表示集合中元素的数量
            /// </summary>
            public int Count
            {
                get { return this._dict._size; }
            }
            /// <summary>
            /// 获取一个值,表示集合是否为只读
            /// </summary>
            public bool IsReadOnly
            {
                get { return true; }
            }
            /// <summary>
            /// 获取指定索引位的Key的值
            /// </summary>
            /// <param name="index">索引</param>
            /// <returns>Key值</returns>
            public K this[int index]
            {
                get { return this._dict.GetIndexValue(index); }
                set { throw new NotSupportedException("Set is an unsupported operation"); }
            }

            /// <summary>
            /// 获取一个值,表示集合是否为线程安全
            /// </summary>
            bool ICollection.IsSynchronized
            {
                get { return false; }
            }
            /// <summary>
            /// 获取线程同步属性
            /// </summary>
            object ICollection.SyncRoot
            {
                get { return this._dict; }
            }
            //方法
            //构造函数
            internal KeyList(ReversibleSortedList<K, V> dictionary)
            {
                this._dict = dictionary;
            }

            public void Add(K key)
            {
                throw new NotSupportedException("集合无法实现添加元素的操作");
            }

            public void Clear()
            {
                throw new NotSupportedException("集合无法实现清除的操作");
            }

            /// <summary>
            /// 集合是否包含指定的键,包含返回True,不包含返回False
            /// </summary>
            /// <param name="key">键值</param>
            /// <returns>是否包含</returns>
            public bool Contains(K key)
            {
                return this._dict.ContainsKey(key);
            }

            public void Insert(int index, K key)
            {
                throw new NotSupportedException("集合不支持插入方法");
            }

            /// <summary>
            /// 将集合中的元素复制到指定的数组集合中
            /// </summary>
            /// <param name="array">数组集合</param>
            /// <param name="arrayIndex">指定集合开始的索引</param>
            public void CopyTo(K[] array, int arrayIndex)
            {
                Array.Copy(this._dict.keys, 0, array, arrayIndex, this._dict.Count);
            }

            public IEnumerator<K> GetEnumerator()
            {
                return new ReversibleSortedList<K, V>.ReversibleSortedListKeyEnumerator(this._dict);
            }

            /// <summary>
            /// 得到指定键值在集合中的索引,不存在返回-1
            /// </summary>
            /// <param name="key">查找的键值</param>
            /// <returns>键值在集合中的索引</returns>
            public int IndexOf(K key)
            {
                if (key == null)
                    throw new ArgumentNullException("key");

                int num1 = Array.BinarySearch<K>(this._dict.keys, 0, this._dict.Count, key, this._dict._sortDirectionComparer);

                if (num1 >= 0)
                    return num1;
                return -1;
            }

            public bool Remove(K key)
            {
                return false;
            }

            /// <summary>
            /// 集合不支持该方法
            /// </summary>
            public void RemoveAt(int index)
            {
                throw new NotSupportedException("集合不支持该方法");
            }

            void ICollection.CopyTo(Array array, int arrayIndex)
            {
                if (array != null && array.Rank != 1)
                    throw new ArgumentException("MultiDimensional arrays are not unsupported");

                try
                {
                    Array.Copy(this._dict.keys, 0, array, arrayIndex, this._dict.Count);
                }
                catch(ArrayTypeMismatchException atme)
                {
                    throw new ArgumentException("InvalidArrayType", atme);
                }
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return new ReversibleSortedList<K, V>.ReversibleSortedListKeyEnumerator(this._dict);
            }
        }

        /// <summary>
        /// 实现字典集合内部的值的操作
        /// </summary>
        [Serializable]
        private sealed class ValueList<K, V> : IList<V>, ICollection<V>, IEnumerable<V>, ICollection, IEnumerable
        {
            //变量
            private ReversibleSortedList<K, V> _dict;
            //属性
            /// <summary>
            /// 获取一个值,表示集合中元素的数量
            /// </summary>
            public int Count
            {
                get { return this._dict._size; }
            }
            /// <summary>
            /// 获取一个值,表示集合是否为只读
            /// </summary>
            public bool IsReadOnly
            {
                get { return true; }
            }
            /// <summary>
            /// 获取指定索引位的Key的值
            /// </summary>
            /// <param name="index">索引</param>
            /// <returns>Key值</returns>
            public V this[int index]
            {
                get { return this._dict.GetIndexKey(index); }
                set { throw new NotSupportedException("Set is an unsupported operation"); }
            }

            /// <summary>
            /// 获取一个值,表示集合是否为线程安全
            /// </summary>
            bool ICollection.IsSynchronized
            {
                get { return false; }
            }
            /// <summary>
            /// 获取线程同步属性
            /// </summary>
            object ICollection.SyncRoot
            {
                get { return this._dict; }
            }
            //方法
            //构造函数
            internal ValueList(ReversibleSortedList<K, V> dictionary)
            {
                this._dict = dictionary;
            }

            public void Add(V value)
            {
                throw new NotSupportedException("集合无法实现添加元素的操作");
            }

            public void Clear()
            {
                throw new NotSupportedException("集合无法实现清除的操作");
            }

            /// <summary>
            /// 集合是否包含指定的键,包含返回True,不包含返回False
            /// </summary>
            /// <param name="key">键值</param>
            /// <returns>是否包含</returns>
            public bool Contains(V value)
            {
                return this._dict.ContainsValue(value);
            }

            /// <summary>
            /// 将集合中的元素复制到指定的数组集合中
            /// </summary>
            /// <param name="array">数组集合</param>
            /// <param name="arrayIndex">指定集合开始的索引</param>
            public void CopyTo(V[] array, int arrayIndex)
            {
                Array.Copy(this._dict.values, 0, array, arrayIndex, this._dict.Count);
            }

            public IEnumerator<V> GetEnumerator()
            {
                return new ReversibleSortedList<K, V>.ReversibleSortedListValueEnumerator(this._dict);
            }
            /// <summary>
            /// 得到指定键值在集合中的索引,不存在返回-1
            /// </summary>
            /// <param name="key">查找的键值</param>
            /// <returns>键值在集合中的索引</returns>
            public int IndexOf(V value)
            {
                return Array.IndexOf<V>(this._dict.values, value, 0, this._dict.Count);
            }

            public void Insert(int index, V value)
            {
                throw new NotSupportedException("集合不支持插入方法");
            }
            /// <summary>
            /// 移除指定的值
            /// </summary>
            /// <param name="value">指定的值</param>
            public bool Remove(V value)
            {
                return false;
            }
            /// <summary>
            /// 集合不支持该方法
            /// </summary>
            public void RemoveAt(int index)
            {
                throw new NotSupportedException("集合不支持该方法");
            }

            void ICollection.CopyTo(Array array, int arrayIndex)
            {
                if (array != null && array.Rank != 1)
                    throw new ArgumentException("MultiDimensional arrays are not unsupported");

                try
                {
                    Array.Copy(this._dict.values, 0, array, arrayIndex, this._dict.Count);
                }
                catch (ArrayTypeMismatchException atme)
                {
                    throw new ArgumentException("InvalidArrayType", atme);
                }
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return new ReversibleSortedList<K, V>.ReversibleSortedListValueEnumerator(this._dict);
            }
        }

        /// <summary>
        /// 键的枚举类
        /// </summary>
        [Serializable]
        private sealed class ReversibleSortedListKeyEnumerator : IEnumerator<TKey>, IDisposable, IEnumerator
        {
            private ReversibleSortedList<TKey, TValue> _ReversibleSortedList;
            private TKey currentKey;
            private int index;
            private int version;

            /// <summary>
            /// 获取枚举的当前值
            /// </summary>
            public TKey Current
            {
                get { return this.currentKey; }
            }

            /// <summary>
            /// 获取枚举的当前值
            /// </summary>
            object IEnumerator.Current
            {
                get
                {
                    if (this.index == 0 || this.index == this._ReversibleSortedList.Count + 1)
                        throw new InvalidOperationException("集合元素在枚举过程中发生变化");
                    return this.currentKey;
                }
            }

            internal ReversibleSortedListKeyEnumerator(ReversibleSortedList<TKey, TValue> ReversibleSortedList)
            {
                this._ReversibleSortedList = ReversibleSortedList;
                this.version = ReversibleSortedList.version;
            }

            /// <summary>
            /// 将枚举索引设置为0,当前键为默认键值
            /// </summary>
            public void Dispose()
            {
                this.index = 0;
                this.currentKey = default(TKey);
            }

            /// <summary>
            /// 尝试枚举集合的下一个元素
            /// </summary>
            /// <returns>如果存在下一个元素返回True,否则返回False</returns>
            /// <exception cref="InvalidOperationException">集合元素在枚举过程中发生变化</exception>
            public bool MoveNext()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("集合元素在枚举过程中发生变化");
                if (this.index < this._ReversibleSortedList.Count)
                {
                    this.currentKey = this._ReversibleSortedList.keys[this.index];
                    this.index++;
                    return true;
                }
                this.index = this._ReversibleSortedList.Count + 1;
                this.currentKey = default(TKey);
                return false;
            }

            /// <summary>
            /// 重置集合枚举 
            /// </summary>
            /// <exception cref="InvalidOperationException">枚举集合版本检查错误</exception>
            void IEnumerator.Reset()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("枚举集合版本检查错误");
                this.index = 0;
                this.currentKey = default(TKey);
            }
        }

        /// <summary>
        /// 值的枚举类
        /// </summary>
        [Serializable]
        private sealed class ReversibleSortedListValueEnumerator : IEnumerator<TValue>, IDisposable, IEnumerator
        {
                        private ReversibleSortedList<TKey, TValue> _ReversibleSortedList;
            private TValue currentValue;
            private int index;
            private int version;

            /// <summary>
            /// 获取枚举的当前值
            /// </summary>
            public TValue Current
            {
                get { return this.currentValue; }
            }

            /// <summary>
            /// 获取枚举的当前值
            /// </summary>
            object IEnumerator.Current
            {
                get
                {
                    if (this.index == 0 || this.index == this._ReversibleSortedList.Count + 1)
                        throw new InvalidOperationException("集合元素在枚举过程中发生变化");
                    return this.currentValue;
                }
            }

            internal ReversibleSortedListValueEnumerator(ReversibleSortedList<TKey, TValue> ReversibleSortedList)
            {
                this._ReversibleSortedList = ReversibleSortedList;
                this.version = ReversibleSortedList.version;
            }

            /// <summary>
            /// 将枚举索引设置为0,当前键为默认键值
            /// </summary>
            public void Dispose()
            {
                this.index = 0;
                this.currentValue = default(TValue);
            }

            /// <summary>
            /// 尝试枚举集合的下一个元素
            /// </summary>
            /// <returns>如果存在下一个元素返回True,否则返回False</returns>
            /// <exception cref="InvalidOperationException">集合元素在枚举过程中发生变化</exception>
            public bool MoveNext()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("集合元素在枚举过程中发生变化");
                if (this.index < this._ReversibleSortedList.Count)
                {
                    this.currentValue = this._ReversibleSortedList.values[this.index];
                    this.index++;
                    return true;
                }
                this.index = this._ReversibleSortedList.Count + 1;
                this.currentValue = default(TValue);
                return false;
            }

            /// <summary>
            /// 重置集合枚举 
            /// </summary>
            /// <exception cref="InvalidOperationException">枚举集合版本检查错误</exception>
            void IEnumerator.Reset()
            {
                if (this.version != this._ReversibleSortedList.version)
                    throw new InvalidOperationException("枚举集合版本检查错误");
                this.index = 0;
                this.currentValue = default(TValue);
            }
        }
        #endregion

    }
}
